package com.disv.support.config;

import java.util.concurrent.ConcurrentHashMap;

public class CacheManagerUtil {
    private static ConcurrentHashMap cacheMap = new ConcurrentHashMap<>();


    //设置布尔值的缓存
    public static boolean setCacheValue(String cacheName, Object obj) {
        cacheMap.put(cacheName, obj);
        return true;
    }

    /**
     * 设置带失效时间的缓存
     *
     * @param cacheName 缓存名称
     * @param obj       obj
     * @param exTime    交货时间（秒）
     * @return boolean
     */
    public static boolean setCacheValueEx(String cacheName, Object obj, long exTime) {
        cacheMap.put(cacheName, obj);
        cacheMap.put(cacheName + "_ex", System.currentTimeMillis() + exTime * 1000);
        return true;
    }

    /**
     * 获得缓存
     *
     * @param cacheName 缓存名称
     * @return {@link Object}
     */
    public static Object getValue(String cacheName) {
        if (checkCacheName(cacheName)) {
            return cacheMap.get(cacheName);
        }
        return null;
    }

    /**
     * 删除某个缓存
     *
     * @param cacheName
     */
    private static void remove(String cacheName) {
        cacheMap.remove(cacheName);
        cacheMap.remove(cacheName + "_HoldTime");
    }

    /**
     * 检查缓存对象是否存在失效时间设置，
     * 若存在，检查其是否已过有效期，如果已经过了则删除该缓存并返回false
     *
     * @param cacheName 缓存名称
     * @return boolean
     */
    private static boolean checkCacheName(String cacheName) {
        if (cacheMap.containsKey(cacheName + "_ex")) {
            Long exTime = (Long) cacheMap.get(cacheName + "_ex");
            if (exTime > System.currentTimeMillis()) {
                return true;
            } else {
                remove(cacheName);
            }
        }
        return false;
    }


}
